package com.xxmassdeveloper.mpchartexample.sqlite.tables;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.xxmassdeveloper.mpchartexample.sqlite.module.Weight;

import java.util.ArrayList;


public class WeightAccessor extends TableAccessor {

    public WeightAccessor(SQLiteDatabase database) {
        super(database);
    }

    private static final String[] weightColumnList =
            new String[]{Tables.mWeightId,
                    Tables.mWeightYear,
                    Tables.mWeightMonth,
                    Tables.mWeightDay,
                    Tables.mWeightValue};

    private Weight getWeight(Cursor c) {
        Weight weight = new Weight();
        weight.setId(c.getInt(c.getColumnIndex(Tables.mWeightId)));
        weight.setYear(c.getString(c.getColumnIndex(Tables.mWeightYear)));
        weight.setMonth(c.getString(c.getColumnIndex(Tables.mWeightMonth)));
        weight.setDay(c.getString(c.getColumnIndex(Tables.mWeightDay)));
        weight.setWeight(c.getFloat(c.getColumnIndex(Tables.mWeightValue)));
        return weight;
    }


    public synchronized void insert(Weight weight) {

        if (weight == null || TextUtils.isEmpty(String.valueOf(weight.getWeight()))) {
            Log.e("111", "note is null or note content is null, can't insert");
            return;
        }

        Log.e("111", "ID = " + weight.getId());

        ContentValues cv = new ContentValues();
        cv.put(Tables.mWeightId, weight.getId());
        cv.put(Tables.mWeightYear, weight.getYear());
        cv.put(Tables.mWeightMonth, weight.getMonth());
        cv.put(Tables.mWeightDay, weight.getDay());
        cv.put(Tables.mWeightValue, weight.getWeight());
        long num = mDatabase.insert(Tables.mWeightTable, null, cv);
        Log.e("111", "insert number " + num);
    }

    public synchronized void deleteLast() {
        ArrayList<Weight> weights = getWeights();
        if (weights.size() > 0) {
            int hashCode = weights.get(weights.size() - 1).getId();
            Log.e("111", "hashCode" + hashCode);
            int num =  mDatabase.delete(Tables.mWeightTable, Tables.mWeightId + " = ?", new String[]{hashCode + ""});
            Log.e("111", "..del ==" + num);
        }
    }

    public ArrayList<Weight> getWeights() {
        ArrayList<Weight> list = new ArrayList<Weight>();
        Cursor cursor = mDatabase.query(Tables.mWeightTable, weightColumnList, null, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
            do {
                list.add(getWeight(cursor));
            } while (cursor.moveToNext());
        }
        if (cursor != null) {
            cursor.close();
        }
        return list;
    }
}
